<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const array = [3,6, 4, 0, 1, 2, 5, 7, 8, 9]
        res = bubble_sort_optimzation(array)
        console.log(...array)
        function bubble_sort(array){
            for (let i = array.length; i>0; i--){
                for (let j=0; j<i; j++){
                    if (array[j] > array[j+1]){
                        let tmp = array[j]
                        array[j] = array[j+1]
                        array[j+1] = tmp
                    }
                }
            }
            return array
        }
        // 在js中，一旦声明了变量就要考虑作用域的问题
        function bubble_sort_optimzation(array){
            let isSwap
            let tmp = 0
            let unorderedBounders = array.length - 1
            let lastSwapAt = 0
            for (let i = 0; i<array.length; i++){
                isSwap = false
                for (let j = 0; j<unorderedBounders; j++){
                    if (array[j] > array[j+1]){
                        tmp = array[j]
                        array[j] = array[j+1]
                        array[j+1] = tmp
                        isSwap = true
                        lastSwapAt = j
                    }
                }
                unorderedBounders = lastSwapAt
                if (!isSwap){
                    break
                }
            } 
            return array
        }
    </script>
</body>
</html>